import logging
import os.path
import shutil

import pytest

from utils.device import Device
from utils.manager import SnapshotThread

BASE_DIR = os.path.dirname(__file__)


def pytest_addoption(parser):
    parser.addoption('--sn', default='')


@pytest.fixture(scope='session', autouse=True)
def device(request):
    sn = request.config.option.sn
    return Device(sn)


@pytest.fixture(scope='module')
def setup_teardown(request, device):
    logging.info('------模块前置操作------')
    current_case = os.path.basename(request.path)[:-3]
    # 日志截图等保存路径
    device.report_path = os.path.realpath(os.path.join(os.path.dirname(request.config.option.htmlpath), current_case))
    logging.info('设置当前用例的报告路径为{}'.format(device.report_path))
    device.resource_path = os.path.join(os.path.dirname(__file__), 'resource')
    os.makedirs(device.report_path, exist_ok=True)
    device.wait_boot_completed()
    os.chdir(BASE_DIR)

    if os.path.exists(device.report_path):
        for f in os.listdir(device.report_path):
            try:
                os.remove(os.path.join(device.report_path, f))
            except:
                pass
    # device.start_hilog()
    # 开一个线程截图
    t = SnapshotThread(device)
    t.start()

    device.wakeup()
    device.set_screen_timeout()
    device.unlock()
    device.go_home()
    device.wait(2)
    win_name, win_id = device.get_focus_window()
    if win_id == '0':
        device.reboot()
        device.unlock()
        device.wait(2)
        device.cancel_usb_dialog()
    elif win_name == 'SystemDialog1':
        device.cancel_usb_dialog()
    elif win_name == 'SystemUi_DropdownPan':
        device.swipe_up_dropdown_pan()
    yield

    logging.info('------模块后置操作------')
    device.go_home()
    device.clear_recent_task()
    device.force_stop(request.param)
    device.clean_app_data(request.param)
    t.stop()
    device.clear_local_tmp()


@pytest.fixture()
def factory_reset(device):
    logging.info('------方法前置------')
    yield
    logging.info('------方法后置------')
    device.factory_reset()
    device.wakeup()
    device.unlock()
    device.go_home()
    win_name, _ = device.get_focus_window()
    if win_name == 'SystemDialog1':
        device.cancel_usb_dialog()
    elif win_name == 'SystemUi_DropdownPan':
        device.swipe_up_dropdown_pan()
